package com.wt.wechatTools;

import android.os.Bundle;
import android.os.Looper;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;

import com.wt.wechatTools.databinding.FragmentRegisterBinding;
import com.wt.wechatTools.tools.MyRequest;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * A simple {@link Fragment} subclass.
 * create an instance of this fragment.
 */
public class FragmentRegister extends Fragment {
    private static final String TAG = "FragmentRegister";
    private String pwd1;
    private String pwd2;
    private String userName;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        FragmentRegisterBinding binding;
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_register, container, false);

        userName = binding.editName.getText().toString();
        pwd1 = binding.editPwd.getText().toString();
        pwd2 = binding.editPwd2.getText().toString();

        binding.btnRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //验证输入框
                if (verifyEdit()) return;
                //开始注册
                registerHttps(binding);
            }
        });
        return binding.getRoot();
    }

    /**
     * 验证输入框
     * @return
     */
    private boolean verifyEdit() {
        if (userName.isEmpty() || pwd1.isEmpty() || pwd2.isEmpty()) {
            Toast.makeText(getContext(), "用户名或密码不能为空！", Toast.LENGTH_SHORT).show();
            return true;
        }

        if (!pwd1.equals(pwd2)) {
            Toast.makeText(getContext(), "2次输入的密码要相同！", Toast.LENGTH_SHORT).show();
            return true;
        }
        return false;
    }

    /**
     * 注册
     *
     * @param binding
     */
    private void registerHttps(com.wt.wechatTools.databinding.FragmentRegisterBinding binding) {
        OkHttpClient okHttpClient = new OkHttpClient();
        RequestBody requestBody = new FormBody.Builder()
                .add("username", String.valueOf(binding.editName.getText()))
                .add("pwd", String.valueOf(binding.editPwd.getText()))
                .add("register_token", MyRequest.register_token)
                .build();
        Request request = new Request.Builder()
                .url(MyRequest.proUrl + "user_register")
                .post(requestBody)
                //增加关闭连接，不让它保持连接。   https://blog.csdn.net/zhangteng22/article/details/52233126
                .addHeader("Connection", "close")
                .build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d(TAG, "onFailure: " + e.getMessage());
                call.cancel();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.d(TAG, "onResponse: " + response.body().string());
                int responseCode = response.code();
                if (responseCode != 200) {
                    //toast无法再主线程执行参考https://blog.csdn.net/weixin_39755659/article/details/89534773
                    Looper.prepare();
                    Toast.makeText(getContext(), "注册失败！", Toast.LENGTH_SHORT).show();
                    Looper.loop();// 进入loop中的循环，查看消息队列
                }
                if (responseCode == 200) {
                    Looper.prepare();
                    Toast.makeText(getContext(), "注册成功！", Toast.LENGTH_SHORT).show();
                    Looper.loop();// 进入loop中的循环，查看消息队列
                }
                response.close();
            }
        });
    }

}